<?php

namespace Modules\Goods\Entities;

use houdunwang\arr\Arr;
use Illuminate\Database\Eloquent\Model;

class Fenlei extends Model
{

    protected $guarded = ['attr'];

    //自关联方法，一对多
    public function child(){
        return $this->hasMany(Fenlei::class,'pid','id');
    }


    //设置一个获取前2级分类的方法
    public static function getTwofenlei(){
        //找到分类表中的所有顶级分类id
        $alltopfenleiid = self::where('pid',0)->pluck('id');
        //找到分类数据表中父级id在$alltopfenleiid数组内的数据
        $sonfenlei = self::whereIn('pid',$alltopfenleiid)->get();
        //获取所有顶级分类的数据
        $alltopfenlei = self::where('pid',0)->get();
        $newfenlei = array_merge($alltopfenlei->toArray(),$sonfenlei->toArray());
        //将新数据返回
        return $newfenlei;
    }


    //存入分类属性中间表的方法
    public function fenleiAttr(){
        return $this->hasMany(FenleiAttr::class);
    }


    //设置一个分类的树状图结构方法
    public static function getTreefenlei(){
        $data = self::get()->toArray();
        $fenlei = Arr::tree($data,'fname','id','pid');
//        dd($fenlei);
        return $fenlei;
    }
}
